<script setup>
import { onMounted, ref, reactive } from 'vue';
import { queryCheckShemaPage, CheckShemaAdd, UpdateById, deleteByIds } from '@/api/checkSchema';
import { ElMessage } from 'element-plus';

// 查询表单（分页+搜索条件）
const queryForm = reactive({
  page: 1,     // 当前页
  pageSize: 5, // 每页条数
  total: 0,    // 总条数
  pages: 1,    // 总页数
  name: '',    // 名称搜索
  type: ''     // 类型搜索（空表示不筛选）
});

// 表格数据
const checkSchemaList = ref([]);
// 选中行的ID（批量删除用）
const selectedIds = ref([]);

// 表单引用（验证用）
const ruleFormRef = ref(null);
// 表单数据（新增/编辑用）
const form = reactive({
  id: null,        // 编辑时的ID
  name: '',        // 名称
  type: 0,         // 类型：0=全检，1=抽检
  method: 0,       // 抽检方式：0=百分比，1=间隔
  values1: null,   // 百分比/间隔值
  values2: null,   // 间隔模式的抽取值
  checkItemId: '', // 检验项目ID
  description: ''  // 描述
});

// 弹窗显隐
const dialogFormVisible = ref(false);
// 弹窗标题
const formTitle = ref('');

// 分页查询
const queryCheckSchemas = async () => {
  try {
    const result = await queryCheckShemaPage(queryForm);
    checkSchemaList.value = result.data.records || [];
    // 同步分页参数
    queryForm.page = result.data.current || 1;
    queryForm.pageSize = result.data.size || 5;
    queryForm.pages = result.data.pages || 1;
    queryForm.total = result.data.total || 0;
  } catch (error) {
    ElMessage.error('查询失败');
  }
};

// 搜索（重置页码后查询）
const handleSearch = () => {
  queryForm.page = 1;
  queryCheckSchemas();
};

// 重置查询条件
const resetQuery = () => {
  queryForm.name = '';
  queryForm.type = '';
  queryForm.page = 1;
  queryCheckSchemas();
};

// 分页-每页条数变化
const handleSizeChange = (val) => {
  queryForm.pageSize = val;
  queryForm.page = 1;
  queryCheckSchemas();
};

// 分页-当前页变化
const handleCurrentChange = (val) => {
  queryForm.page = val;
  queryCheckSchemas();
};

// 表格多选变化（同步选中ID）
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入检验方案名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2-50 个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择检验方案类型', trigger: 'change' }
  ],
  method: [
    { required: true, message: '请选择抽检方式', trigger: 'change' }
  ],
  values1: [
    { required: true, message: '请输入数值', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value <= 0) callback(new Error('请输入大于0的数字'));
      else callback();
    }, trigger: 'blur' }
  ],
  values2: [
    { required: true, message: '请输入抽取值', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value <= 0) callback(new Error('请输入大于0的数字'));
      else callback();
    }, trigger: 'blur' }
  ],
  checkItemId: [
    { required: true, message: '请选择检验项目', trigger: 'blur' }
  ]
});

// 清空表单
const clearForm = () => {
  form.id = null;
  form.name = '';
  form.type = 0;
  form.method = 0;
  form.values1 = null;
  form.values2 = null;
  form.checkItemId = '';
  form.description = '';
  if (ruleFormRef.value) ruleFormRef.value.clearValidate();
};

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false;
  clearForm();
};

// 打开新增弹窗
const openAddDialog = () => {
  clearForm();
  formTitle.value = '新增检验方案';
  dialogFormVisible.value = true;
};

// 打开编辑弹窗（回显行数据）
const handleEdit = (row) => {
  clearForm();
  Object.assign(form, { ...row }); // 深拷贝行数据到表单
  formTitle.value = '编辑检验方案';
  dialogFormVisible.value = true;
};

// 提交表单（新增/编辑）
const submitForm = async () => {
  try {
    await ruleFormRef.value.validate(); // 表单验证
    if (form.id) {
      await UpdateById(form); // 编辑
      ElMessage.success('更新成功！');
    } else {
      await CheckShemaAdd(form); // 新增
      ElMessage.success('新增成功！');
    }
    closeDialog();
    queryCheckSchemas(); // 刷新列表
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

// 单条删除（简化：直接删除，无确认弹窗）
const handleDelete = async (id) => {
  try {
    await deleteByIds([id]); // 调用删除接口
    ElMessage.success('删除成功');
    queryCheckSchemas(); // 刷新列表
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 批量删除（简化：直接删除，无确认弹窗）
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }
  try {
    await deleteByIds(selectedIds.value.join(',')); // 数组转字符串传参
    ElMessage.success('批量删除成功');
    queryCheckSchemas();
    selectedIds.value = []; // 清空选中
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 页面加载时初始化查询
onMounted(() => {
  queryCheckSchemas();
});
</script>

<template>
 <!-- 新增/编辑弹窗 -->
<el-dialog v-model="dialogFormVisible" :title="formTitle" width="500px">
  <el-form
    ref="ruleFormRef"
    :rules="rules"
    :model="form"
    label-width="100px"
    style="max-width: 600px"
  >
    <!-- 名称 -->
    <el-form-item label="名称:" prop="name">
      <el-input v-model="form.name" placeholder="请输入检验方案名称" />
    </el-form-item>

    <!-- 类型（全检/抽检） -->
    <el-form-item label="类型:" prop="type">
      <el-radio-group v-model="form.type">
        <el-radio :label="0">全检</el-radio>
        <el-radio :label="1">抽检</el-radio>
      </el-radio-group>
    </el-form-item>

    <!-- 抽检方式（百分比/间隔，仅抽检时显示） -->
    <el-form-item v-if="form.type === 1" label="抽检方式:" prop="method">
      <el-radio-group v-model="form.method">
        <el-radio :label="0">百分比</el-radio>
        <el-radio :label="1">间隔</el-radio>
      </el-radio-group>
    </el-form-item>

    <!-- 百分比值（仅“抽检 + 百分比”时显示） -->
    <el-form-item v-if="form.type === 1 && form.method === 0" label="值:" prop="values1">
      <el-input v-model.number="form.values1" placeholder="请输入百分比（如 10）" suffix="%" />
    </el-form-item>

    <!-- 间隔值 + 抽取值（合并为一行，带文字提示） -->
    <el-form-item v-if="form.type === 1 && form.method === 1" label="值:" required>
      <span>每间隔</span>
      <el-input 
        v-model.number="form.values1" 
        placeholder="请输入间隔值" 
        style="width: 120px; margin: 0 8px;" 
        prop="values1"
      />
      <span>抽取</span>
      <el-input 
        v-model.number="form.values2" 
        placeholder="请输入抽取值" 
        style="width: 120px; margin: 0 8px;" 
        prop="values2"
      />
    </el-form-item>

    <!-- 检验项目（输入框与按钮同行） -->
    <el-form-item label="检验项目:" prop="checkItemId" style="display: flex; align-items: center;">
      <el-input 
        v-model="form.checkItemId" 
        placeholder="请选择检验项目" 
        style="flex: 1; margin-right: 8px;" 
      />
      <el-button type="primary">选择</el-button>
    </el-form-item>

    <!-- 描述（强制宽度，确保显示） -->
   <el-form-item label="描述:">
  <el-input 
    v-model="form.description" 
    type="textarea" 
    placeholder="请输入描述内容" 
    rows="3" 
    style="width: 100%;"
  />
</el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="closeDialog">取消</el-button>
    <el-button type="primary" @click="submitForm">确定</el-button>
  </template>
</el-dialog>

  <!-- 查询表单 -->
  <el-form :model="queryForm" :inline="true" style="margin-bottom: 16px;">
    <el-form-item label="名称:">
      <el-input v-model="queryForm.name" placeholder="请输入检验方案名称" clearable />
    </el-form-item>

    <el-form-item label="类型:" style="width:200px">
      <el-select 
        v-model="queryForm.type" 
        placeholder="请选择类型" 
        clearable
        @change="handleSearch"
      >
        <el-option label="全检" :value="0"></el-option>
        <el-option label="抽检" :value="1"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon> 查询
      </el-button>
      <el-button @click="resetQuery">重置</el-button>
      <el-button type="primary" @click="openAddDialog">
        <el-icon><Plus /></el-icon> 新增
      </el-button>
      <el-button 
        type="danger" 
        @click="handleBatchDelete" 
        :disabled="selectedIds.length === 0"
      >
        <el-icon><Delete /></el-icon> 批量删除
      </el-button>
    </el-form-item>
  </el-form>

  <!-- 检验方案表格（支持横向滚动，操作列固定） -->
  <el-table 
    :data="checkSchemaList" 
    style="width: 100%; overflow-x: auto;" 
    align="center"
    @selection-change="handleSelectionChange"
    border
  >
    <!-- 多选列 -->
    <el-table-column type="selection" width="55" />
    <el-table-column label="序号" type="index" width="80" />
    <el-table-column prop="name" label="名称" width="150" />
    
    <!-- 类型列（用Tag美化，调整宽度确保显示） -->
    <el-table-column label="类型" width="100">
      <template #default="scope">
        <el-tag v-if="scope.row.type == 0" type="danger">全检</el-tag>
        <el-tag v-else-if="scope.row.type == 1" type="success">抽检</el-tag>
      </template>
    </el-table-column>
    

    <el-table-column label="抽检方式" width="100">
      <template #default="scope">
        <el-tag v-if="scope.row.method == 0" type="danger">百分比</el-tag>
        <el-tag v-else-if="scope.row.method == 1" type="success">间隔</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="值" width="200">
  <template #default="scope">
    <!-- 对 type/method 做字符串→数字转换，同时兜底空值 -->
    <template v-if="Number(scope.row.type) === 1">
      <template v-if="Number(scope.row.method) === 0 && scope.row.values1">
        {{ scope.row.values1 }}%
      </template>
      <template v-else-if="Number(scope.row.method) === 1 && scope.row.values1 && scope.row.values2">
        每间隔{{ scope.row.values1 }} 抽取{{ scope.row.values2 }}
      </template>
      <!-- 抽检但值为空时的兜底 -->
      <template v-else>
        （值为空）
      </template>
    </template>
    <template v-else>
      ——
    </template>
  </template>
</el-table-column>

    <el-table-column prop="description" label="描述" width="200" />
    <el-table-column prop="createdTime" label="创建时间" width="180" />
    <el-table-column prop="updateTime" label="修改时间" width="180" />
    <el-table-column prop="createdBy" label="创建人" width="150" />
    
    <!-- 操作列（固定在右侧） -->
    <el-table-column label="操作" width="180" fixed="right">
      <template #default="scope">
        <el-button type="primary" size="small" @click="handleEdit(scope.row)">
          <el-icon><Edit /></el-icon> 编辑
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">
          <el-icon><Delete /></el-icon> 删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
    v-model:current-page="queryForm.page"
    v-model:page-size="queryForm.pageSize"
    :page-sizes="[5, 10, 15, 20]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="queryForm.total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin-top: 16px; text-align: right;"
  />
</template>

<style scoped>
/* 可选：调整表格滚动体验 */
.el-table {
  margin-bottom: 16px;
}                            
</style>